package com.appspot.zcmjqm.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.appspot.zcmjqm.app.model.Service;
import com.appspot.zcmjqm.app.model.category.ServiceCategory;
import com.appspot.zcmjqm.app.model.quote.ServiceQuote;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@org.springframework.stereotype.Service
public class ServiceServiceJPAImpl implements ServiceService {
	
	@Autowired
	private EntityManager entityManager;
	
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Transactional
	public List<ServiceCategory> getAllCategories() {
		List<?> l = entityManager.createQuery("select from ServiceCategory").getResultList();
		List<ServiceCategory> categories = new ArrayList<ServiceCategory>();
		for (Object o : l) {
			categories.add((ServiceCategory) o);
		}
		return categories;
	}

	@Transactional
	public List<Service> getByCategory(String categoryKey) {
		ServiceCategory serviceCategory = new ServiceCategory();
		Key k = KeyFactory.stringToKey(categoryKey);
		serviceCategory.setKey(k);
		Query query = entityManager.createQuery("select from Service where serviceCategory = :cat");
		query.setParameter("cat", serviceCategory);
		List<?> l = query.getResultList();
		List<Service> services = new ArrayList<Service>();
		for (Object o : l) {
			services.add((Service) o);
		}
		return services;
	}

	@Transactional
	public Service getById(String key) {
		Key k = KeyFactory.stringToKey(key);
		return entityManager.find(Service.class, k);
	}

	@Transactional
	public void saveQuote(ServiceQuote serviceQuote) {
		entityManager.merge(serviceQuote);
	}

}
